package com.zfx.service.impl;

import com.github.pagehelper.PageHelper;
import com.zfx.mapper.IContractRemindMapper;
import com.zfx.mapper.ILevel1SystemMapper;
import com.zfx.mapper.ISecondarySystemFunctionMessageMapper;
import com.zfx.pojo.ContractRemind;
import com.zfx.pojo.Level1System;
import com.zfx.pojo.SecondarySystemFuncationMessage;
import com.zfx.service.ILevel1SystemService;
import com.zfx.util.DataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.*;

/**
 * @description:
 * @author: zfx
 * @version: 1.0
 * @time: 2020-05-10 15:23
 * <p>
 * 修改历史：
 * 修改日期      修改人员    版本    内容
 * 2020-05-10   zfx       1.0
 */
@Service
public class Level1SystemServiceImpl implements ILevel1SystemService {

    @Autowired
    private ILevel1SystemMapper level1SystemMapper;

    @Autowired
    private ISecondarySystemFunctionMessageMapper secondarySystemFunctionMessageMapper;

    @Autowired
    private IContractRemindMapper contractRemindMapper;

    private static final String FIND_ALL_NUM = "0";  //查询所有
    private static final String NOT_FORWARD_NUM = "1";  //未转发
    private static final String FORWARD_NOT_CONFIRM_NUM = "2";  //已转发未确认
    private static final String CONFIRM_NUM = "3";  //已确认

    private static final int FOUNDATION_PLATFORM_SYSTEM_NUM = 1;
    private static final int INTERFACE_SYSTEM_NUM = 2;
    private static final int SERVICE_SYSTEM_NUM = 3;
    private static final int APPLICATION_APPLET_SYSTEM_NUM = 41;
    private static final int APPLICATION_H5_SYSTEM_NUM = 42;
    private static final int APPLICATION_CLIENT_SYSTEM_NUM = 43;
    private static final int APPLICATION_PC_SYSTEM_NUM = 44;
    private static final int APPLICATION_TENCENT_SYSTEM_NUM = 45;

    @Transactional(readOnly = true)
    @Override
    public Map<String, Object> findByLevel1System(Level1System level1System, String userId, String stateNum, int page, int size) {

        String condition = userId+"_"+stateNum; //封装条件 201_1
        Map<String,Object> dataMap = new HashMap<>();
        ArrayList<Level1System> finalList = new ArrayList<>();

        if(stateNum.equals(FIND_ALL_NUM)) { //查询全部

            int dataSize = level1SystemMapper.findByLevel1System(level1System).size();
            PageHelper.startPage(page,size);
            List<Level1System> originalList = level1SystemMapper.findByLevel1System(level1System);
            for (Level1System system : originalList) {
                String state = system.getState();
                if(String.valueOf(state.charAt(state.length()-1)).equals(CONFIRM_NUM)) {  //最后一个人确认了等于全部人确认了
                    system.setState(CONFIRM_NUM);
                } else {
                    String str = userId + "_";
                    int lastIndexOf = state.lastIndexOf(str) + str.length();
                    if (String.valueOf(state.charAt(lastIndexOf)).equals(FORWARD_NOT_CONFIRM_NUM)) {
                        system.setState(FORWARD_NOT_CONFIRM_NUM);
                    } else {
                        system.setState(NOT_FORWARD_NUM);
                    }
                }
            }
            dataMap.put("level1SystemList", originalList);
            dataMap.put("dataSize", dataSize);
            return dataMap;
        }

        List<Level1System> originalList = level1SystemMapper.findByLevel1System(level1System); //查出来的原始数据
        List<Level1System> processedList = new ArrayList<>();
        if(stateNum.equals(CONFIRM_NUM)) {  //最后一个人确认了等于全部人确认了
            for (Level1System system : originalList) {
                String state = system.getState();
                if (stateNum.equals(String.valueOf(state.charAt(state.length()-1)))) {
                    system.setState(CONFIRM_NUM);
                    processedList.add(system); //加入列表
                }
            }
        } else {
            String str = userId + "_";
            for (Level1System system1 : originalList) {
                String state = system1.getState();
                if(!CONFIRM_NUM.equals(String.valueOf(state.charAt(state.length()-1)))) {
                    int lastIndexOf = state.lastIndexOf(str) + str.length();
                    if (stateNum.equals(String.valueOf(state.charAt(lastIndexOf)))) {
                        system1.setState(stateNum);
                        processedList.add(system1); //加入列表
                    }
                }
            }
        }
        //手动分页
        for(int i = (page-1)*size; i < page*size; i++) {
            if(i < processedList.size()) {
                finalList.add(processedList.get(i));
            } else {
                break;
            }
        }
        dataMap.put("level1SystemList", finalList);
        dataMap.put("dataSize", processedList.size());

        return dataMap;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteById(Integer level1SystemId) {
        return level1SystemMapper.deleteByPrimaryKey(level1SystemId);
    }

    @Override
    public Level1System findByUrl(Level1System level1System) {
        return level1SystemMapper.selectOne(level1System);
    }

    @Override
    public List<String> transmitMsg(Integer level1SystemId) {
        String state = level1SystemMapper.selectByPrimaryKey(level1SystemId).getState();

        String[] split = state.split("-");

        List<String> numList = new ArrayList<>();

        for ( String str : split ) {
            numList.add(str.substring(0, str.length()-2));
        }

        return numList;
    }

    @Transactional(readOnly = true)
    @Override
    public Level1System findById(Integer level1SystemId) {
        return level1SystemMapper.selectByPrimaryKey(level1SystemId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(Level1System level1System) {
        return level1SystemMapper.updateByPrimaryKeySelective(level1System);
    }

    @Override
    public String isOk(int level1SystemId, String userId) {

        String state = level1SystemMapper.selectByPrimaryKey(level1SystemId).getState();
        String code = state.substring(state.length()-1);

        if(code.equals(CONFIRM_NUM)) {
            return "已确认";
        } else if(code.equals(NOT_FORWARD_NUM)){
            String[] strings = state.split("-");
            String string = strings[strings.length - 1];
            if(!string.equals(userId+"_1")) {
                return "已转发未确认";
            }
        }
        return "";
    }

    @Override
    public int create(int templateId, int userId) {

        //新建一级系统
        Level1System level1System = new Level1System();
        level1System.setState(userId+"_1");
        level1System.setTemplateId(String.valueOf(templateId));
        level1System.setCreateUserId(userId);
        level1System.setCreateDate(new Date());

        level1SystemMapper.insert(level1System);
        int level1SystemId = level1System.getLevel1SystemId();
        System.out.println("level1SystemId:  " + level1SystemId);

        String url = "?tableId="+level1SystemId+"&preId="+userId+"&localtime="+ DataUtil.getCurrentTime();
        level1System.setSendUrl(url);
        level1SystemMapper.updateByPrimaryKeySelective(level1System);

        //新建二级系统
        SecondarySystemFuncationMessage funcationMessage = new SecondarySystemFuncationMessage();
        funcationMessage = new SecondarySystemFuncationMessage();
        funcationMessage.setLevel1SystemId(level1SystemId);
        funcationMessage.setTypeId(FOUNDATION_PLATFORM_SYSTEM_NUM);
        secondarySystemFunctionMessageMapper.insert(funcationMessage);
        funcationMessage = new SecondarySystemFuncationMessage();
        funcationMessage.setLevel1SystemId(level1SystemId);
        funcationMessage.setTypeId(INTERFACE_SYSTEM_NUM);
        secondarySystemFunctionMessageMapper.insert(funcationMessage);
        funcationMessage = new SecondarySystemFuncationMessage();
        funcationMessage.setLevel1SystemId(level1SystemId);
        funcationMessage.setTypeId(SERVICE_SYSTEM_NUM);
        secondarySystemFunctionMessageMapper.insert(funcationMessage);
        funcationMessage = new SecondarySystemFuncationMessage();
        funcationMessage.setLevel1SystemId(level1SystemId);
        funcationMessage.setTypeId(APPLICATION_APPLET_SYSTEM_NUM);
        secondarySystemFunctionMessageMapper.insert(funcationMessage);
        funcationMessage = new SecondarySystemFuncationMessage();
        funcationMessage.setLevel1SystemId(level1SystemId);
        funcationMessage.setTypeId(APPLICATION_H5_SYSTEM_NUM);
        secondarySystemFunctionMessageMapper.insert(funcationMessage);
        funcationMessage = new SecondarySystemFuncationMessage();
        funcationMessage.setLevel1SystemId(level1SystemId);
        funcationMessage.setTypeId(APPLICATION_CLIENT_SYSTEM_NUM);
        secondarySystemFunctionMessageMapper.insert(funcationMessage);
        funcationMessage = new SecondarySystemFuncationMessage();
        funcationMessage.setLevel1SystemId(level1SystemId);
        funcationMessage.setTypeId(APPLICATION_PC_SYSTEM_NUM);
        secondarySystemFunctionMessageMapper.insert(funcationMessage);
        funcationMessage = new SecondarySystemFuncationMessage();
        funcationMessage.setLevel1SystemId(level1SystemId);
        funcationMessage.setTypeId(APPLICATION_TENCENT_SYSTEM_NUM);
        secondarySystemFunctionMessageMapper.insert(funcationMessage);

        //新建提醒
        ContractRemind remind = new ContractRemind();
        remind.setTableId(level1SystemId);
        remind.setState(0);
        contractRemindMapper.insert(remind);

        return level1SystemId;
    }
}
